//
// Created on 2024/4/22.
//
// Node APIs are not fully supported. To solve the compilation error of the interface cannot be found,
// please include "napi/native_api.h".

#include "thread_loader.h"
#include "glesshader.h"
#include "mlog.h"
static glesmain *glesmain_;
const EGLint CONTEXT_ATTRIBS[] = {EGL_CONTEXT_CLIENT_VERSION, 2, EGL_NONE};
const  EGLint surfaceAttribs[]={EGL_NONE};
static void Loader_Init() {
    {
        // Create context.
        glesmain_->m_eglContext_loader =
            eglCreateContext(glesmain_->m_eglDisplay, glesmain_->m_eglConfig, glesmain_->m_eglContext_gfx, CONTEXT_ATTRIBS);
        int err4 = eglGetError();
        MLOGFormat("eglCreateContext For Loader %{public}d %{public}04x", glesmain_->m_eglContext_gfx, err4);
        EGLSurface eglSurface = eglCreatePbufferSurface(glesmain_->m_eglDisplay, glesmain_->m_eglConfig, surfaceAttribs);
        //EGL_BAD_ATTRIBUTE 0x3004
        int err5 = eglGetError();
        MLOGFormat("eglCreatePbufferSurface For Loader %{public}d %{public}04x",eglSurface, err5);
        if (!eglMakeCurrent(glesmain_->m_eglDisplay, eglSurface, eglSurface,
                            glesmain_->m_eglContext_loader)) {
            int err = eglGetError();
            
            auto errstr = eglQueryString(glesmain_->m_eglDisplay, err);
            // 3006 EGL_BAD_CONTEXT
            // #define EGL_BAD_DISPLAY 0x3008
            // #define EGL_BAD_MATCH 0x3009
            MERRORFormat("eglMakeCurrent failed %{public}04x %{public}s", err, errstr);
            return;
        }

        const char *ptrver = (const char *)glGetString(GL_VERSION);
        MLOGFormat("GLVersion %{public}s", ptrver);

    }
}
static void Loader_Loop() {
    sem_wait(&glesmain_->sem_gfx_init); // 等待初始化线程完事儿
    Loader_Init();
    { gles_shadermgr::Init(); }
    while (true) {
        //接受加载指令，所有的加载都在loader线程搞
    }
}

void Start_Thread_Loader(glesmain *pglesmain) {
    glesmain_ = pglesmain;


    std::thread *thread = new std::thread(Loader_Loop);
}